package com.wtwd.campus.utils;

import com.wtwd.campus.entity.AttendanceRecordData;
import com.wtwd.campus.entity.OrgExpiration;
import com.wtwd.campus.entity.SysOrg;
import com.wtwd.campus.service.AttendanceRulesService;
import com.wtwd.campus.service.SysOrgService;
import com.wtwd.campus.service.SysUserService;
import com.wtwd.campus.service.WarningRecordService;
import com.wtwd.campus.wx.utils.PushModel;
import com.wtwd.campus.wx.utils.WxUtils;
import org.apache.commons.lang.StringUtils;
import org.jeewx.api.core.req.model.message.TemplateMessageSendResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class ExpirationTimer {
    private static final Logger logger = LoggerFactory.getLogger(ExpirationTimer.class);

    @Autowired
    SysOrgService sysOrgService;
    @Autowired
    WarningRecordService warningRecordService;
    @Autowired
    AttendanceRulesService attendanceRulesService;

    @Scheduled(cron = "0 0 0,11,12,16,20 * * ?")
    public void saveExpirationMess() {
        //选择执行事件
        int a=0;
        long time = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour == 0) {
            //存储组织到期信息
            saveOrgExpireMess();
        } else if (hour == 11) {
            //推送上午签到考勤信息
            pushSignMorningMess();
        } else if (hour == 12) {
            //推送上午签退考勤信息
            pushLeaveMorningMess();
        } else if (hour == 16) {
            //推送下午签到考勤信息
            pushSignAfternoonMess();
        } else if (hour == 20) {
            //推送下午签退考勤信息
            pushLeaveAfternoonMess();
        }
    }

    /**
     * 存储到期组织信息
     */
    public void saveOrgExpireMess() {
        //从数据库中查询距离过期时间还有五天的组织
        long now = System.currentTimeMillis();
        Long yesTime = now - (1000 * 60 * 60 * 24);
        Long expirTimeMax = now + 1000 * 60 * 60 * 24 * 6;
        Long expirTimeMin = now + 1000 * 60 * 60 * 24 * 5;
        //还有五天过期的组织
        List<Map<String, Object>> expirationOrg = sysOrgService.getExpirationOrg(expirTimeMax, expirTimeMin);
        List<OrgExpiration> list1 = new ArrayList<>();
        expirationOrg.stream().forEach(e -> {
            String orgName = (String) e.get("org_name");
            String orgCode = (String) e.get("org_code");
            Long expiresTime = (Long) e.get("expires_time");
            OrgExpiration orgExpiration = new OrgExpiration();
            orgExpiration.setIfRead(0);
            orgExpiration.setOrgCode(orgCode);
            orgExpiration.setSysName(orgName);
            orgExpiration.setType(0);
            orgExpiration.setExpirationTime(expiresTime);
            orgExpiration.setCreateTime(now);
            list1.add(orgExpiration);
        });
        //已经过期的组织
        List<Map<String, Object>> overdueSysOrg = sysOrgService.getExpirationOrg(now, yesTime);
        overdueSysOrg.stream().forEach(e -> {
            String orgName = (String) e.get("org_name");
            String orgCode = (String) e.get("org_code");
            Long expiresTime = (Long) e.get("expires_time");
            OrgExpiration orgExpiration = new OrgExpiration();
            orgExpiration.setIfRead(0);
            orgExpiration.setOrgCode(orgCode);
            orgExpiration.setSysName(orgName);
            orgExpiration.setType(1);
            orgExpiration.setExpirationTime(expiresTime);
            orgExpiration.setCreateTime(now);
            list1.add(orgExpiration);
        });
        //存储提示信息
        if (list1.size() > 0) {
            Integer integer = warningRecordService.addOrgExpirationList(list1);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("/存储组织过期提示信息，时间：".concat(sdf.format(new Date())));
    }

    /**
     * 获取今日信息
     *
     * @return
     */
    public List<Object> getTodayInfo() {
        //计算今天是礼拜几
        int[] arr = {7, 1, 2, 3, 4, 5, 6};
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int week = arr[calendar.get(Calendar.DAY_OF_WEEK) - 1];
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND,0);
        //获取今日的凌晨时间
        long dayTime = calendar.getTimeInMillis();
        List<Object> list = new ArrayList<>();
        list.add(week);
        list.add(dayTime);
        return list;
    }

    /**
     * 推送上午签到考勤信息
     */
    public void pushSignMorningMess() {
        List<Object> todayInfo = getTodayInfo();
        //查询今日上午需要签到但是没有打卡记录的未打卡学生
        List<Map<String, Object>> noRecordStuList = attendanceRulesService.getNoRecordStuIdList((Integer) todayInfo.get(0), 1, (Long) todayInfo.get(1));
        //查询今日上午需要签到且有打卡记录的未打卡学生
        List<Integer> recordStuIdList = attendanceRulesService.getRecordStuIdList((Integer) todayInfo.get(0), 1, (Long) todayInfo.get(1));
        //将没有打卡记录的学生的打卡记录进行补全
        List<Integer> noRecordStuIdList = addNoRecordMess(noRecordStuList, todayInfo, 1);
        if (recordStuIdList != null) {
            recordStuIdList.addAll(noRecordStuIdList);
            if (recordStuIdList.size() > 0) {
                //查询所有未打卡学生信息并进行微信消息推送
                List<Map<String, Object>> pushMess = attendanceRulesService.getPushMess(recordStuIdList);
                pushMess.stream().forEach(e -> {
                    String openId = (String) e.get("open_id");
                    if (!StringUtils.isBlank(openId)) {
                        String stuName = (String) e.get("student_name");
                        String content = (stuName).concat("同学上午有一条未签到信息，请悉知。");
                        String schoolName = (String) e.get("school_name");
                        TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, "无", schoolName, stuName.concat("同学未打卡，请您关注，谢谢配合！"));
                        template.setUrl("");
                        template.setTouser(openId);
                        //推送信息
                        WxUtils.pushMsg(template);
                    }
                });
            }
        }
        //查询上午签到正常的学生信息并进行推送
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> normalRecordPushMess = attendanceRulesService.getNormalRecordPushMess((Long) todayInfo.get(1), 1);
        normalRecordPushMess.stream().forEach(e -> {
            String openId = (String) e.get("open_id");
            if (!StringUtils.isBlank(openId)) {
                Long time = (Long) e.get("sign_morning_time");
                String stuName = (String) e.get("student_name");
                String content = (stuName).concat("同学已经在上午打卡到校，请悉知。");
                String schoolName = (String) e.get("school_name");
                TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, sdf.format(time), schoolName, stuName.concat("同学已正常到校，请您放心！"));
                template.setUrl("");
                template.setTouser(openId);
                //推送信息
                WxUtils.pushMsg(template);
            }
        });
        //查询上午打卡迟到同学信息并进行推送
        List<Map<String, Object>> beLateRecordPushMess = attendanceRulesService.getBeLateRecordPushMess((Long) todayInfo.get(1), 1);
        beLateRecordPushMess.stream().forEach(e -> {
            String openId = (String) e.get("open_id");
            if (!StringUtils.isBlank(openId)) {
                Long time = (Long) e.get("sign_morning_time");
                String stuName = (String) e.get("student_name");
                String content = (stuName).concat("同学在上午有一条迟到信息，请悉知。");
                String schoolName = (String) e.get("school_name");
                TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, sdf.format(time), schoolName, stuName.concat("同学打卡迟到，请您关注，谢谢配合！"));
                template.setUrl("");
                template.setTouser(openId);
                //推送信息
                WxUtils.pushMsg(template);
            }
        });
    }


    /**
     * 推送上午签退考勤信息
     */
    public void pushLeaveMorningMess() {
        List<Object> todayInfo = getTodayInfo();
        //查询今日上午需要签退但是没有打卡记录的未打卡学生
        List<Map<String, Object>> noRecordStuList = attendanceRulesService.getNoRecordStuIdList((Integer) todayInfo.get(0), 2, (Long) todayInfo.get(1));
        //查询今日上午需要签退且有打卡记录的未打卡学生
        List<Integer> recordStuIdList = attendanceRulesService.getRecordStuIdList((Integer) todayInfo.get(0), 2, (Long) todayInfo.get(1));
        //将没有打卡记录的学生的打卡记录进行补全
        List<Integer> noRecordStuIdList = addNoRecordMess(noRecordStuList, todayInfo, 2);
        if (recordStuIdList != null) {
            recordStuIdList.addAll(noRecordStuIdList);
            if (recordStuIdList.size() > 0) {
                //查询所有未打卡学生信息并进行微信消息推送
                List<Map<String, Object>> pushMess = attendanceRulesService.getPushMess(recordStuIdList);
                pushMess.stream().forEach(e -> {
                    String openId = (String) e.get("open_id");
                    if (!StringUtils.isBlank(openId)) {
                        String stuName = (String) e.get("student_name");
                        String content = (stuName).concat("同学上午有一条未签退信息，请悉知。");
                        String schoolName = (String) e.get("school_name");
                        TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, "无", schoolName, stuName.concat("同学上午未签退，请您关注，谢谢配合！"));
                        template.setUrl("");
                        template.setTouser(openId);
                        //推送信息
                        WxUtils.pushMsg(template);
                    }
                });
            }
        }
        //查询上午签退正常的学生信息并进行推送
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> normalRecordPushMess = attendanceRulesService.getNormalRecordPushMess((Long) todayInfo.get(1), 2);
        normalRecordPushMess.stream().forEach(e -> {
            String openId = (String) e.get("open_id");
            if (!StringUtils.isBlank(openId)) {
                Long time = (Long) e.get("leave_morning_time");
                String stuName = (String) e.get("student_name");
                String content = (stuName).concat("同学已经在上午打卡离校，请悉知。");
                String schoolName = (String) e.get("school_name");
                TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, sdf.format(time), schoolName, stuName.concat("同学已正常离校，请您关注！"));
                template.setUrl("");
                template.setTouser(openId);
                //推送信息
                WxUtils.pushMsg(template);
            }
        });
        //查询上午早退同学信息并进行推送
        List<Map<String, Object>> beLateRecordPushMess = attendanceRulesService.getLeaveEarlyRecordPushMess((Long) todayInfo.get(1), 2);
        beLateRecordPushMess.stream().forEach(e -> {
            String openId = (String) e.get("open_id");
            if (!StringUtils.isBlank(openId)) {
                Long time = (Long) e.get("leave_morning_time");
                String stuName = (String) e.get("student_name");
                String content = (stuName).concat("同学有一条早退信息，请悉知。");
                String schoolName = (String) e.get("school_name");
                TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, sdf.format(time), schoolName, stuName.concat("同学上午存在早退现象，请您关注，谢谢配合！"));
                template.setUrl("");
                template.setTouser(openId);
                //推送信息
                WxUtils.pushMsg(template);
            }
        });
    }


    /**
     * 推送下午签到考勤信息
     */
    public void pushSignAfternoonMess() {
        List<Object> todayInfo = getTodayInfo();
        //查询今日下午需要签到但是没有打卡记录的未打卡学生
        List<Map<String, Object>> noRecordStuList = attendanceRulesService.getNoRecordStuIdList((Integer) todayInfo.get(0), 3, (Long) todayInfo.get(1));
        //查询今日下午需要签到且有打卡记录的未打卡学生
        List<Integer> recordStuIdList = attendanceRulesService.getRecordStuIdList((Integer) todayInfo.get(0), 3, (Long) todayInfo.get(1));
        //将没有打卡记录的学生的打卡记录进行补全
        List<Integer> noRecordStuIdList = addNoRecordMess(noRecordStuList, todayInfo, 3);
        if (recordStuIdList != null) {
            recordStuIdList.addAll(noRecordStuIdList);
            if (recordStuIdList.size() > 0) {
                //查询所有未打卡学生信息并进行微信消息推送
                List<Map<String, Object>> pushMess = attendanceRulesService.getPushMess(recordStuIdList);
                pushMess.stream().forEach(e -> {
                    String openId = (String) e.get("open_id");
                    if (!StringUtils.isBlank(openId)) {
                        String stuName = (String) e.get("student_name");
                        String content = (stuName).concat("同学下午有一条未签到信息，请悉知。");
                        String schoolName = (String) e.get("school_name");
                        TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, "无", schoolName, stuName.concat("同学未打卡，请您关注，谢谢配合！"));
                        template.setUrl("");
                        template.setTouser(openId);
                        //推送信息
                        WxUtils.pushMsg(template);
                    }
                });
            }
        }
        //查询下去签到正常的学生信息并进行推送
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> normalRecordPushMess = attendanceRulesService.getNormalRecordPushMess((Long) todayInfo.get(1), 3);
        normalRecordPushMess.stream().forEach(e -> {
            String openId = (String) e.get("open_id");
            if (!StringUtils.isBlank(openId)) {
                Long time = (Long) e.get("sign_afternoon_time");
                String stuName = (String) e.get("student_name");
                String content = (stuName).concat("同学已经在下午打卡到校，请悉知。");
                String schoolName = (String) e.get("school_name");
                TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, sdf.format(time), schoolName, stuName.concat("同学已正常到校，请您放心！"));
                template.setUrl("");
                template.setTouser(openId);
                //推送信息
                WxUtils.pushMsg(template);
            }
        });
        //查询下午打卡迟到同学信息并进行推送
        List<Map<String, Object>> beLateRecordPushMess = attendanceRulesService.getBeLateRecordPushMess((Long) todayInfo.get(1), 3);
        beLateRecordPushMess.stream().forEach(e -> {
            String openId = (String) e.get("open_id");
            if (!StringUtils.isBlank(openId)) {
                Long time = (Long) e.get("sign_afternoon_time");
                String stuName = (String) e.get("student_name");
                String content = (stuName).concat("同学在下午有一条迟到信息，请悉知。");
                String schoolName = (String) e.get("school_name");
                TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, sdf.format(time), schoolName, stuName.concat("同学打卡迟到，请您关注，谢谢配合！"));
                template.setUrl("");
                template.setTouser(openId);
                //推送信息
                WxUtils.pushMsg(template);
            }
        });
    }


    /**
     * 推送下午签退考勤信息
     */
    public void pushLeaveAfternoonMess() {
        List<Object> todayInfo = getTodayInfo();
        //查询今日下午需要签退但是没有打卡记录的未打卡学生
        List<Map<String, Object>> noRecordStuList = attendanceRulesService.getNoRecordStuIdList((Integer) todayInfo.get(0), 4, (Long) todayInfo.get(1));
        //查询今日下午需要签退且有打卡记录的未打卡学生
        List<Integer> recordStuIdList = attendanceRulesService.getRecordStuIdList((Integer) todayInfo.get(0), 4, (Long) todayInfo.get(1));
        //将没有打卡记录的学生的打卡记录进行补全
        List<Integer> noRecordStuIdList = addNoRecordMess(noRecordStuList, todayInfo, 4);
        if (recordStuIdList != null) {
            recordStuIdList.addAll(noRecordStuIdList);
            if (recordStuIdList.size() > 0) {
                //查询所有未打卡学生信息并进行微信消息推送
                List<Map<String, Object>> pushMess = attendanceRulesService.getPushMess(recordStuIdList);
                pushMess.stream().forEach(e -> {
                    String openId = (String) e.get("open_id");
                    if (!StringUtils.isBlank(openId)) {
                        String stuName = (String) e.get("student_name");
                        String content = (stuName).concat("同学在下午有一条未签退信息，请悉知。");
                        String schoolName = (String) e.get("school_name");
                        TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, "无", schoolName, stuName.concat("同学下午未签退，请您关注，谢谢配合！"));
                        template.setUrl("");
                        template.setTouser(openId);
                        //推送信息
                        WxUtils.pushMsg(template);
                    }
                });
            }
        }
        //查询下午签退正常的学生信息并进行推送
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> normalRecordPushMess = attendanceRulesService.getNormalRecordPushMess((Long) todayInfo.get(1), 4);
        normalRecordPushMess.stream().forEach(e -> {
            String openId = (String) e.get("open_id");
            if (!StringUtils.isBlank(openId)) {
                Long time = (Long) e.get("leave_afternoon_time");
                String stuName = (String) e.get("student_name");
                String content = (stuName).concat("同学已经在下午打卡离校，请悉知。");
                String schoolName = (String) e.get("school_name");
                TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, sdf.format(time), schoolName, stuName.concat("同学已正常离校，请您关注！"));
                template.setUrl("");
                template.setTouser(openId);
                //推送信息
                WxUtils.pushMsg(template);
            }
        });
        //查询下午早退同学信息并进行推送
        List<Map<String, Object>> beLateRecordPushMess = attendanceRulesService.getLeaveEarlyRecordPushMess((Long) todayInfo.get(1), 4);
        beLateRecordPushMess.stream().forEach(e -> {
            String openId = (String) e.get("open_id");
            if (!StringUtils.isBlank(openId)) {
                Long time = (Long) e.get("leave_afternoon_time");
                String stuName = (String) e.get("student_name");
                String content = (stuName).concat("同学在下午有一条早退信息，请悉知。");
                String schoolName = (String) e.get("school_name");
                TemplateMessageSendResult template = PushModel.createAttendanceRecordTemplate(content, stuName, sdf.format(time), schoolName, stuName.concat("同学下午存在早退现象，请您关注，谢谢配合！"));
                template.setUrl("");
                template.setTouser(openId);
                //推送信息
                WxUtils.pushMsg(template);
            }
        });
    }


    /**
     * 补全未打卡同学的打卡记录
     *
     * @param noRecordStuList
     * @param todayInfo
     * @param status
     * @return
     */
    public List<Integer> addNoRecordMess(List<Map<String, Object>> noRecordStuList, List<Object> todayInfo, int status) {
        List<Integer> noRecordStuIdList = new ArrayList<>();
        if (noRecordStuList != null && noRecordStuList.size() > 0) {
            List<AttendanceRecordData> addList = new ArrayList<>();
            noRecordStuList.stream().forEach(e -> {
                if (!StringUtils.isBlank((String) e.get("rfid"))) {
                    AttendanceRecordData record = new AttendanceRecordData();
                    record.setLeaveAfternoon(4);
                    record.setSignAfternoon(4);
                    record.setSignMorning(4);
                    record.setLeaveMorning(4);
                    if (status == 1) {
                        record.setSignMorning(1);
                    } else if (status == 2) {
                        record.setLeaveMorning(1);
                    } else if (status == 3) {
                        record.setSignAfternoon(1);
                    } else if (status == 4) {
                        record.setLeaveAfternoon(1);
                    }
                    record.setStudentId((Integer) e.get("student_id"));
                    record.setTime((Long) todayInfo.get(1));
                    record.setDeviceId((Integer) e.get("device_id"));
                    record.setRfid((String) e.get("rfid"));
                    noRecordStuIdList.add((Integer) e.get("student_id"));
                    addList.add(record);
                }
            });
            //补全未打卡同学的打卡信息
            if (addList.size() > 0) {
                int i = attendanceRulesService.addAttendanceRecord(addList);
            }
        }
        return noRecordStuIdList;
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.stream().forEach(e -> {
            System.out.println("aaa");
            System.out.println(e);
        });
    }
}
